/**
 * @author banglong
 * @date 2016/10/27
 */
define(['avalon', 'Layer', 'tools', 'rootPath', 'depsSelectDialog', 'GoodsSelectDialog', 'chooseCondition',
    'conditionsUtils', 'rtstoreQueryApi', 'text!../html/index/report/RTStoreQueryTemp.html!strip'
  ],
  function (avalon, layer, tools, rootPath, depsSelectDialog, GoodsSelectDialog, chooseCondition,
    conditionsUtils, api, htmlTemp) {

    return function () {

      var self = this;
      var runtimeParam;
      var getRuntimeParam = function () {
        return {
          timeObj: {}
        };
      };

      var rtstoreQueryVm;
      var getVmOption = function () {
        return {
          $id: 'rtstoreQuery',
          breadcrumb: '',

          rtsTableHeader: ['科室名称', '物品代码', '物品名称', '型号规格', '计量单位', '数量'],
          rtsTableRow: ['DeptAccountName', 'PackageCode', 'PackageName', 'GoodsSpec', 'BoxUnit', 'Counts'],
          rtsTableData: [],

          detailTableHeader: ['物品代码', '物品名称', '型号规格', '计量单位', '价格', '货号', '数量', '有效期开始', '有效期结束'],
          detailTableRow: ['PackageCode', 'PackageName', 'GoodsSpec', 'BoxUnit', 'Price', 'GoodsNo', 'Counts', 'ExpireDateStart', 'ExpireDateEnd'],
          detailTableData: [],

          goodsID: '',
          goodsName: '',
          deptAccountName: '',
          deptAccountID: '',
          packageBigCatName: '',
          packageBigCatID: '',
          tableComponentsID: ['xxx_rts_main', 'xxx_rts_detail'],

          chooseDesp: function () {
            tools.throttle(runtimeParam.timeObj, function () {
              // 科室选择框
              var deps = JSON.parse(localStorage.getItem('deps'));
              depsSelectDialog.init(deps,
                function (dep) {
                  rtstoreQueryVm.deptAccountName = dep.Ksmc.trim();
                  rtstoreQueryVm.deptAccountID = dep.DeptAccountID;
                },
                rtstoreQueryVm.deptAccountName);
            });
          },

          choosePackageBig: function () {
            tools.throttle(runtimeParam.timeObj, function () {
              var param = {
                type: 6
              };
              param.chooseConditionsFunc = function (condition) {
                rtstoreQueryVm.packageBigCatName = condition.PackageBigCatName;
                rtstoreQueryVm.packageBigCatID = condition.PackageBigCatID;
              };
              param.searchValue = rtstoreQueryVm.packageBigCatName;
              chooseCondition.init(param);
            });
          },

          chooseGoods: function () {
            tools.throttle(runtimeParam.timeObj, function () {
              new GoodsSelectDialog().init({
                Openparm: runtimeParam.Openparm,
                isGYKS: true,
                getAll: true,
                searchValue: rtstoreQueryVm.goodsName, //初始的查询信息
                pushChooseGoods: function (data) { // 选择物品
                  rtstoreQueryVm.goodsName = data.GoodsName;
                  rtstoreQueryVm.goodsID = data.GoodsID;
                }
              });
            });
          },

          back: function () {
            var main = document.querySelector('#main');
            main.removeChild(tools.getFirstElementChild(main));
            runtimeParam.checkBreadcrumb();
            runtimeParam.showMenu();
            self.destroy();
          },

          search: function () {
            if (!rtstoreQueryVm.deptAccountID) {
              tools.handleError('请选择科室');
              return;
            }

            var conditions = conditionsUtils.rtstoreQuery({
              DeptAccountID: rtstoreQueryVm.deptAccountID,
              PackageBigCatID: rtstoreQueryVm.packageBigCatID,
              PackageID: rtstoreQueryVm.goodsID
            });

            rtstoreQuery(conditions, rtstoreQueryVm);
          },

          handleClick: function (index, data) {
            getFormalPackageBatchLayout(data.PackageID, rtstoreQueryVm.deptAccountID).then(function (jsonResult) {

              if (jsonResult.issuccess !== 0) {
                return Promise.reject('获取信息失败');
              }

              var result = JSON.parse(jsonResult.result);
              rtstoreQueryVm.detailTableData.splice(0, rtstoreQueryVm.detailTableData.length);
              rtstoreQueryVm.detailTableData.pushArray(result);

            })['catch'](function (ex) {
              tools.handleError(ex);
            });
          },

          excelExport: function () {
            if (rtstoreQueryVm.detailTableData.length === 0 && !runtimeParam.excelParam) {
              tools.handleError('请确认查询结果不为空');
              return;
            }
            tools.throttle(runtimeParam.timeObj, function () {

              var url = rootPath.getRootPath() + "export/rtstoerQueryDetail";
              
              if (tools.isIEByActiveObject()) {
                tools.DownLoadFile({
                  url: url.split('?')[0],
                  data: {
                    name: '正式库存查询',
                    className: runtimeParam.excelParam.className,
                    method: runtimeParam.excelParam.method,
                    packageID: runtimeParam.excelParam.packageID,
                    deptAccountID: runtimeParam.excelParam.deptAccountID,
                    fieldName: rtstoreQueryVm.detailTableHeader.$model.join(','),
                    fieldValueName: rtstoreQueryVm.detailTableRow.$model.join(',')
                  }
                });
              } else {
                url += '?name=' + encodeURIComponent(encodeURIComponent('正式库存查询'));
                url += '&className=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.className));
                url += '&method=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.method));
                url += '&packageID=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.packageID));
                url += '&deptAccountID=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.deptAccountID));
                url += '&fieldName=' + encodeURIComponent(encodeURIComponent(JSON.parse(JSON.stringify(rtstoreQueryVm.detailTableHeader.$model)).join(',')));
                url += '&fieldValueName=' + encodeURIComponent(encodeURIComponent(JSON.parse(JSON.stringify(rtstoreQueryVm.detailTableRow.$model)).join(',')));
                window.location.href = url;
              }
            });
          }
        };
      };

      function rtstoreQuery(conditions, rtstoreQueryVm) {
        var loadIndex = layer.load();
        rtstoreQueryVm.detailTableData.splice(0, rtstoreQueryVm.detailTableData.length);
        api.rtstoreQuery({
          className: 'PackageStoreManager',
          method: 'RTStoreQuery',
          condition: JSON.stringify(conditions)
        }).then(function (jsonResult) {

          if (jsonResult.issuccess !== 0) {
            return Promise.reject('获取信息失败');
          }

          var result = JSON.parse(jsonResult.result);
          rtstoreQueryVm.rtsTableData.splice(0, rtstoreQueryVm.rtsTableData.length);
          rtstoreQueryVm.rtsTableData.pushArray(result);
          layer.close(loadIndex);
          if (result.length === 0) {
            return Promise.reject('exit');
          } else {
            return getFormalPackageBatchLayout(result[0].PackageID, rtstoreQueryVm.deptAccountID);
          }

        }).then(function (jsonResult) {

          if (jsonResult.issuccess !== 0) {
            return Promise.reject('获取信息失败');
          }

          var result = JSON.parse(jsonResult.result);
          rtstoreQueryVm.detailTableData.pushArray(result);

        })['catch'](function (ex) {
          layer.close(loadIndex);
          tools.handleError(ex);
        });
      }

      function getFormalPackageBatchLayout(packageID, deptAccountID) {
        runtimeParam.excelParam = {
          className: 'PackageStoreManager',
          method: 'GetFormalPackageBatchLayout',
          packageID: packageID,
          deptAccountID: deptAccountID,
          showZeroBatch: false
        };
        return api.getFormalPackageBatchLayout(runtimeParam.excelParam);
      }

      function setVMWatch(rtstoreQueryVm) {
        rtstoreQueryVm.$watch('goodsName', function (value) {
          if (!value) {
            rtstoreQueryVm.goodsID = '';
          }
        });
        rtstoreQueryVm.$watch('deptAccountName', function (value) {
          if (!value) {
            rtstoreQueryVm.deptAccountName = '';
          }
        });
        rtstoreQueryVm.$watch('packageBigCatName', function (value) {
          if (!value) {
            rtstoreQueryVm.packageBigCatID = '';
          }
        });
      }

      this.init = function ($main, param) {
        $main.append(htmlTemp);
        rtstoreQueryVm = tools.initAvalonVm(avalon, getVmOption(), ".rtsrore-query");

        runtimeParam = getRuntimeParam();
        runtimeParam = Object.assign(runtimeParam, param);

        rtstoreQueryVm.breadcrumb = runtimeParam.breadcrumb; // 路径
        rtstoreQueryVm.deptAccountName = runtimeParam.currentDept.Ksmc.trim();
        rtstoreQueryVm.deptAccountID = runtimeParam.currentDept.DeptAccountID;

        setVMWatch(rtstoreQueryVm);
        tools.bindDestroyMethod(self.destroy);
      };

      this.destroy = function () {
        runtimeParam = null;
        rtstoreQueryVm = null;
        tools.destroy(getVmOption());
      };
    };
  });